package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.constant.enums.AllAuditActionStatusEnum;
import com.engine4cloud.tdf.common.core.constant.enums.AuditBusinessTypeEnum;
import com.engine4cloud.tdf.common.core.constant.enums.CorFileTypeEnum;
import com.engine4cloud.tdf.common.core.constant.enums.NormalAuditActionStatusEnum;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.core.util.lambda.Actions;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.SpUsualOutConvert;
import com.engine4cloud.tdf.supervision.dto.create.SpAuditActionResultCreateDTO;
import com.engine4cloud.tdf.supervision.dto.create.SpUsualOutCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxAreaQueryDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxFileQueryDTO;
import com.engine4cloud.tdf.supervision.dto.query.SpUsualOutQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxAreaResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.SpUsualOutResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.SpNormalPreActionUpdateDTO;
import com.engine4cloud.tdf.supervision.dto.update.SpUsualOutUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.SpUsualOutEntity;
import com.engine4cloud.tdf.supervision.mapper.SpUsualOutMapper;
import com.engine4cloud.tdf.supervision.service.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

/**
 * 经常性跨市县活动
 *
 * @author wenjie
 * @date 2024-04-11 10:22:38
 */
@Service
public class SpUsualOutServiceImpl extends ServiceImpl<SpUsualOutMapper, SpUsualOutEntity> implements SpUsualOutService {
    @Resource
    private JzdxService jzdxService;
    @Resource
    private JzdxAreaService areaService;
    @Resource
    private SpAuditResultService auditResultService;
    @Resource
    private JzdxFileService fileService;

    @Override
    public PageInfo<SpUsualOutResultDTO> pageList(Params pageable, SpUsualOutQueryDTO dto) {
        IPage<SpUsualOutEntity> page = super.page(Pages.page(pageable), wrapper(dto));
        return Pages.convert(page, SpUsualOutConvert.INSTANCE::convert);
    }

    @Override
    public Boolean create(SpUsualOutCreateDTO dto) {
        Optional.ofNullable(jzdxService.getByCode(dto.getRybh()))
                .orElseThrow(() -> new ValidateCodeException("矫正对象数据不存在"));
        TdfUser user = SecurityUtils.getUser();

        //保存跨市县活动信息
        SpUsualOutEntity entity = SpUsualOutConvert.INSTANCE.create(dto, user.getTenantId(), NormalAuditActionStatusEnum.CREATE);
        //设置跨市县地区信息
        this.setArea(entity);
        super.save(entity);
        //保存文件信息
        this.saveInstrumentList(dto, entity, user);
        //设置审核信息
        return auditResultService.create(
                new SpAuditActionResultCreateDTO(
                        entity.getRybh(),
                        entity.getLcbh(),
                        "",
                        AuditBusinessTypeEnum.USUAL_OUT,
                        AllAuditActionStatusEnum.CREATE,
                        user.getUsername(),
                        entity.getTenantId(),
                        user.getDeptId()
                ));
    }

    @Override
    public Boolean update(SpUsualOutUpdateDTO dto) {
        SpUsualOutEntity old = Optional.ofNullable(super.getById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));
        TdfUser user = SecurityUtils.getUser();
        //转换
        SpUsualOutEntity entity = SpUsualOutConvert.INSTANCE.update(dto);
        this.setArea(entity);
        super.updateById(entity);
        //保存文件信息
        this.updateInstrumentList(dto, old, user);
        return true;
    }

    @Override
    public SpUsualOutResultDTO getById(Long id) {
        SpUsualOutResultDTO result = Optional.ofNullable(SpUsualOutConvert.INSTANCE.convert(super.getById(id)))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));
        //设置法律文书信息
        this.setInstrumentList(result);
        return result;
    }

    @Override
    public SpUsualOutResultDTO getByBatch(String batch) {
        return SpUsualOutConvert.INSTANCE.convert(super.getOne(wrapper(new SpUsualOutQueryDTO(batch))));
    }

    @Override
    public void changeAction(SpNormalPreActionUpdateDTO dto) {
        SpUsualOutEntity entity = Optional.ofNullable(this.getOne(wrapper(new SpUsualOutQueryDTO(dto.getRybh(), dto.getLcbh()))))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        entity.setPreAction(dto.getAction());
        super.updateById(entity);
    }

    private void setArea(SpUsualOutEntity entity) {
        JzdxAreaResultDTO area = areaService.getArea(new JzdxAreaQueryDTO(entity.getQwdszs(), entity.getQwdszd(), entity.getQwdszx(), Long.parseLong(entity.getQwdxz())));
        entity.setQwdszsmc(area.getProvince().getName());
        entity.setQwdszdmc(area.getCity().getName());

        Actions.apply(Objects.nonNull(area.getCounty()), () -> entity.setQwdszxmc(area.getCounty().getName()));
        Actions.apply(Objects.nonNull(area.getVillage()), () -> entity.setQwdxzmc(area.getVillage().getName()));
    }

    private void saveInstrumentList(SpUsualOutCreateDTO dto, SpUsualOutEntity entity, TdfUser user) {
        fileService.batchSaveFile(new JzdxFileQueryDTO(entity.getRybh(), entity.getLcbh(), CorFileTypeEnum.CORRECTOR_USUAL_OUT), dto.getInstrumentList(), user);
    }

    private void updateInstrumentList(SpUsualOutUpdateDTO dto, SpUsualOutEntity entity, TdfUser user) {
        fileService.batchUpdateFile(new JzdxFileQueryDTO(entity.getRybh(), entity.getLcbh(), CorFileTypeEnum.CORRECTOR_USUAL_OUT), dto.getInstrumentList(), user);
    }

    private void setInstrumentList(SpUsualOutResultDTO dto) {
        JzdxFileQueryDTO query = new JzdxFileQueryDTO(dto.getRybh(), dto.getLcbh(), CorFileTypeEnum.CORRECTOR_USUAL_OUT);
        dto.setInstrumentList(fileService.findList(query));
    }

    private LambdaQueryWrapper<SpUsualOutEntity> wrapper(SpUsualOutQueryDTO query) {
        LambdaQueryWrapper<SpUsualOutEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(SpUsualOutEntity::getId, v));
        Queries.accept(query.getRybh(), v -> wrapper.eq(SpUsualOutEntity::getRybh, v));
        Queries.accept(query.getLcbh(), v -> wrapper.eq(SpUsualOutEntity::getLcbh, v));
        Queries.accept(query.getPreAction(), v -> wrapper.eq(SpUsualOutEntity::getPreAction, v));
        return wrapper;
    }
}